package com.dong.dongweather;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.dong.dongweather.db.DataBaseAdapter;
import com.dong.dongweather.db.User;

public class LoginActivity extends Activity implements View.OnClickListener {

    private EditText etName;
    private EditText etPassword;
    private CheckBox keepPassword;
    private Button btnLogin;
    private Button btnRegistered;
    private TextView tvForget;
    private DataBaseAdapter dbAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        dbAdapter = new DataBaseAdapter(this);
        initView();
        btnLogin.setOnClickListener(this);
        btnRegistered.setOnClickListener(this);
    }

    private void initView() {
        etName = findViewById(R.id.et_name);
        etPassword = findViewById(R.id.et_password);
        keepPassword = findViewById(R.id.keep_password);
        btnLogin = findViewById(R.id.btn_login);
        btnRegistered = findViewById(R.id.btn_registered);
        tvForget = findViewById(R.id.tv_forget);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_login:
                //【1】获取输入框的值
                String name = etName.getText().toString().trim();
                String password = etPassword.getText().toString().trim();
                //【2】判断是否为空
                if(!TextUtils.isEmpty(name) & !TextUtils.isEmpty(password)){
                    //登录
                    User user = dbAdapter.find(name);
                    if(user != null){
                        String username = user.getUsername();
                        String userPassword = user.getPassword();
                        if(username.equals(name)){
                            if(userPassword.equals(password)){
                                Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
                                startActivity(new Intent(this, WeatherActivity.class));
                                finish();

                            }else {
                                Toast.makeText(this, "密码错误", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }else {
                        Toast.makeText(this, "帐号不存在，请注册！", Toast.LENGTH_SHORT).show();
                    }


                }else {

                }
                break;

            case R.id.btn_registered:
                startActivity(new Intent(this,RegisteredActivity.class));
                break;
        }
    }


}

